<?php
namespace app\controller;

use app\BaseController;
use app\model\User;
use mailer\facade\Mailer;
use think\facade\Cache;
use think\facade\Session;
use think\captcha\facade\Captcha;
use Firebase\JWT\JWT;
use Firebase\JWT\JWK;
use Firebase\JWT\Key;



class Auth extends BaseController
{
    // 设置发送邮件的最小时间间隔(秒)
    const SEND_MAIL_INTERVAL = 60;

     /**
      * 输入用户名和密码创建用户
      * @param string $username 用户名
      * @param string $passwd 密码
      * @param string $email 邮箱
      * @return string $token
      */
      public function createUser($username='', $passwd='', $email='')
      {
        // 验证码邮箱验证码
        if(Session::get('code')!= $this->request->post('mail_code')){
            return json([
                'code' => 400,
                'msg' => '邮箱验证码错误,请填写正确邮箱验证码!'
            ]);
        }
        Session::delete('code');

        // 内容为空验证
        if (empty($username) || empty($passwd) || empty($email)) {
            return json([
                'code' => 400,
                'msg' => '用户名、密码、EMAIL不能为空！'
            ]);
        }

        $userModel = new User;

        $user = [
            'username' => $username,
            'passwd' => $passwd,
        ];
        $user['token'] = JWT::encode($user, config('jtw.jwt_key'), 'HS256');
        $user['email'] = $email;

        // 加密密码
        $user['passwd'] = password_hash($passwd, PASSWORD_DEFAULT);
        // 检查用户是否已经存在
        $userCheck = $userModel->where('username', $username)->find();
        if ($userCheck) {
            return json([
                'code' => 400,
                'msg' => '用户已存在'
            ]);
        }

        
        $save = $userModel->save($user);
        if (!$save) {
            return json([
                'code' => 400,
                'msg' => '创建用户失败'
            ]);
        }
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $user['token']
        ]);
      }
    /**
    * 查询用户信息
    * @param string $token
    * @return array $user
    */
    public function getUserInfo($token='')
    {
        // 验证token
        $decoded = JWT::decode($token, new Key(config('jtw.jwt_key'), 'HS256'));
        $where = [
            'username' => $decoded->username,
            'passwd' => $decoded->passwd,
            'status'=>1
        ];
        $user = User::where($where)->field('username,email,token,created_time,template,remark')->find();
        if (!$user) {
            return json([
                'code' => 400,
                'msg' => '用户不存在',
                'data' => []
            ]);
        }
        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $user
        ]);
    }

    /**
     * 发送验证邮箱
     * @param string $email
     * @return string
     */
    public function sendEmail($email='')
    {
        // 验证图形码
        if(!captcha_check( $this->request->post('captcha') )){
            return json([
                'code' => 404,
                'msg' => '验证码错误'
            ]);
        }
        if (empty($email)) {
            return json([
                'code' => 404,
                'msg' => '邮箱不能为空'
            ]);
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return json([
                'code' => 404,
                'msg' => '邮箱格式不正确'
            ]);
        }

         // 验证邮箱是否已注册
         $user = User::where('email', $email)->find();
         if ($user) {
             return json([
                 'code' => 404,
                 'msg' => '邮箱已注册'
             ]);
         }


        // 获取用户ID或会话ID作为缓存键的一部分
        $userId = Session::get('user_id', '');
        $sessionId = Session::getId();
        $cacheKey = 'last_send_mail_time_' . ($userId ?: $sessionId);

        // 获取上次发送邮件的时间戳
        $lastSendTime = Cache::get($cacheKey, 0);

        // 计算距离上次发送邮件的时间间隔
        $timeSinceLastSend = time() - $lastSendTime;

        if ($timeSinceLastSend < self::SEND_MAIL_INTERVAL) {
            return json([
                'code' => 429,
                'msg' => '请求过于频繁,请稍后再试'
            ]);
        }

       
        // 发送验证码
        // 生成6位验证码并发送到邮箱
        $code = rand(100000, 999999);
        // 添加标题
        $subject = '【邮箱验证码】';
        $content = '<h1>'.$subject.'</h1><p>您的验证码是：'.$code.'</p>';
        // 发送邮件
        Mailer::to($email)
            ->subject($subject)
            ->html($content)
            ->send();

        // 记录当前发送时间
        Cache::set($cacheKey, time());
        // 验证码存入用户session
        session('code', $code);
        return json([
            'code' => 200,
            'msg' => '验证码发送成功,请查收邮件!'
        ]);
    }
}